<?php

namespace app\weixin\controller;

use app\weixin\model\KnowledgeSubjectModel;
use think\Db;

//题库
class Questions extends Base
{
	public function _initialize(){
		parent::_initialize();
	}

	public function index(){
        $map = [];
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $lists = db('questions')
        		->alias('q')
        		// ->join('user u', 'u.id = q.user_id')
        		->join('knowledge_subject s', 's.id = q.subject_id')
        		->field('q.*, s.name')
        		->where(['q.status'=>['>',-1]])
        		->order('q.id desc')
        		->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $_list = array();
        foreach ($lists as $val) {
            $_t = $val;
            $_t['answer'] = unserialize($val['answer']);
            $_list[] = $_t;
        }
        $this->assign("lists",$_list);
        $this->assign("page", $lists->render());
        return $this->fetch();
    }

     //添加题库
    public function add_questions(){
        $KnowledgeSubjectModel = new KnowledgeSubjectModel();
        $subject = $KnowledgeSubjectModel->getAllSubject();
        $arr = $KnowledgeSubjectModel->subject($subject);
        if(request()->isPost()){
            $post = input('post.');
            $data['subject_id'] = $post['subject_id'];
            $data['grad_id'] = $post['grad_id'];
            // $data['user_id'] = $this->user_info['id'];
            // $data['user_id'] = 212;
            // $data['user_name'] = $this->user_info['user_name'];
            // $data['user_name'] = 'name';
            $data['title'] = $post['title'];
            $data['create_time'] = time(); 

            $arr_a = ['id'=>1,'name'=>$post['answer_a'],'is_right'=>1];
            $arr_b = ['id'=>2,'name'=>$post['answer_b'],'is_right'=>0];
            $arr_c = ['id'=>3,'name'=>$post['answer_c'],'is_right'=>0];
            $arr_d = ['id'=>4,'name'=>$post['answer_d'],'is_right'=>0];
            // $arr = array();
            // array_unshift($arr,$arr_a,$arr_b,$arr_c,$arr_d);
            $arr = [$arr_a,$arr_b,$arr_c,$arr_d];
            $data['answer'] = serialize($arr);
           
            $res = db('questions')->insertGetId($data);
            return $this->success('操作成功');
        }
//        $lists = db('knowledge_subject')->field('id,name')->select();
//         dump($arr);
        $grad = db('grad')->order('sort')->select();//段位
        $this->assign('grad',$grad);

        $this->assign('lists',$arr);
        return $this->fetch();
    }

    //修改
    public function edit_questions(){
        $id = input('id');
        if(request()->isPost()) {
            $post = input('post.');
            $data['subject_id'] = $post['subject_id'];
            $data['grad_id'] = $post['grad_id'];
            $data['title'] = $post['title'];

            $arr_a = ['id'=>1,'name'=>$post['answer_a'],'is_right'=>1];
            $arr_b = ['id'=>2,'name'=>$post['answer_b'],'is_right'=>0];
            $arr_c = ['id'=>3,'name'=>$post['answer_c'],'is_right'=>0];
            $arr_d = ['id'=>4,'name'=>$post['answer_d'],'is_right'=>0];
            $arr = [$arr_a,$arr_b,$arr_c,$arr_d];
            $data['answer'] = serialize($arr);

            $res = db('questions')->where(['id'=>$id])->update($data);
            return $this->success('操作成功');
        }

        $KnowledgeSubjectModel = new KnowledgeSubjectModel();
        $subject = $KnowledgeSubjectModel->getAllSubject();
        $arr = $KnowledgeSubjectModel->subject($subject);

        $grad = db('grad')->order('sort')->select();//段位
        $this->assign('grad',$grad);

        $data = db::name('questions')->where(['id'=>$id])->find();  
        $answer = unserialize($data['answer']);
        if(is_array($answer)) {
            $data['answer_a'] = $answer[0]['name'];
            $data['answer_b'] = $answer['1']['name'];
            $data['answer_c'] = $answer['2']['name'];
            $data['answer_d'] = $answer['3']['name'];
        }
        //$_list['id'] = $data['id'];
        //$_list['title'] = $data['title'];
        //$_list['subject_id'] = $data['subject_id'];
        $this->assign('data',$data);
        $this->assign('lists',$arr);
        return $this->fetch('add_questions');
    }

    //删除题目
    public function del_questions(){
        $id = input('id');
        $res = db('questions')->where(['id'=>$id])->update(['status'=>-1]);
        return $this->success('操作成功');
    }

    //审核
    public function questions_auth(){
        $ids = array_unique(input( 'ids/a', 0 ) );
        $status = input('status',0);
        if(!empty($ids)){
            db('questions')->where('id','IN',$ids)->update(['status'=>$status]);
            return $this->success('操作成功');
        }

    }
    
    //上传题库文件
    function setting() {
        $map=[];
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数

        $list = db( 'questions_batch_record' )->where ( $map )->order ( 'id desc' )->paginate($pagesize,false,array('query' => array_splice($param,1)));
         $KnowledgeSubjectModel = new KnowledgeSubjectModel();
        $subject = $KnowledgeSubjectModel->getAllSubject();
        $arr = $KnowledgeSubjectModel->subject($subject);

        $grad = db('grad')->order('sort')->select();//段位
        $this->assign('grad',$grad);

        $this->assign('lists',$arr);

        $this->assign ( 'list_data',$list );
        $this->assign ( 'page', $list->render() );
        $this->assign ( 'status_arr', ['0'=>'作废','1'=>'未处理','2'=>'已处理','-1'=>'处理失败']);
         
        return $this->fetch();
    }

    //保存信息
    function save_setting() {
        \think\Loader::import('org.Excel', EXTEND_PATH);//导入第三方类库文件

        if(request()->isPost()){
            $post = request()->post();
            $import_total = \Excel::excel_get_data_size(realpath(UPLOAD_PATH).$post['url']);

            $subject_id = $post['subject_id'];
            $post['subject_name'] = db('knowledge_subject')->where(['id'=>$subject_id])->value('name');

            $post['batch_no'] = 'BN'.date('YmdHis');
            $post['import_total'] = $import_total-1;//从第二条开始计算
            $post['create_time'] = time();
            unset($post['file_id']);
            $res = db('questions_batch_record')->insertGetId($post);
            if(!empty($res)){
                $this->success('添加成功！');
            }else{
                $this->error('添加失败！');
            }
        }
    }

    //导入题库
    function import_questions(){
        $id = input('id');//题库批次记录id
        $subject_id = input('subject_id',1);//科目id
        $data_arr = [];

        if(!empty($id)){
            $questions = db('questions_batch_record')->where(['id'=>$id,'status'=>1])->find();
            if(empty($questions))$this->error('导入失败，该批次数据已处理!');
            \think\Loader::import('org.Excel', EXTEND_PATH);//导入第三方类库文件
            $start=2;//起始行
            $limit=10000;//最大10000数量
            $data = \Excel::excel_get_data(realpath(UPLOAD_PATH).$questions['url'],$start,$limit);//读取excel数据
            $json['keep'] = $data['keep'];
            $json['start'] = $data['start'];
            $json['progress'] = $data['progress'];
            
            $i=0;
            
            foreach($data['data'] as $row => $val){
                $answer_arr = [];
                $data_arr[$i]['title'] = $val['A'];
                $answer_arr[] = ['id'=>1,'name'=>$val['B'],'is_right'=>1];
                $answer_arr[] = ['id'=>2,'name'=>$val['C'],'is_right'=>0];
                $answer_arr[] = ['id'=>3,'name'=>$val['D'],'is_right'=>0];
                $answer_arr[] = ['id'=>4,'name'=>$val['E'],'is_right'=>0];
                $data_arr[$i]['answer'] = serialize($answer_arr);
                $data_arr[$i]['subject_id'] = $questions['subject_id'];//科目
                $data_arr[$i]['grad_id'] = $questions['grad_id'];
                $data_arr[$i]['source_type'] = 0;//系统
                $data_arr[$i]['status'] = 1;//通过
                $data_arr[$i]['create_time'] = time();

                $i++;
            }
            if(!empty($data_arr)){//导入题库
                $ret = db('questions')->insertAll($data_arr);
                db('questions_batch_record')->where(['id'=>$id])->update(['status'=>2]);//更新批量导入批次记录
                $this->success('导入成功！');
            }else{
                $this->error('导入失败！');
            }
            //var_export($data_arr);exit;
        }else{
            $this->error('导入失败！');
        }

    }

    //批量删除题目
    public function DelAll_questions(){
        $ids = array_unique(input( 'ids/a', 0 ) );        
        $status = input('status',0);
        if(!empty($ids)){
            db('questions')->where('id','IN',$ids)->update(['status'=>$status]);
            return $this->success('操作成功');
        }
    }
    
}